package com.trade.action;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.trade.form.ReposityForm;
import com.trade.model.Reposity;
import com.trade.model.User;
import com.trade.service.IReposityService;

/**
 * @author Lin Yang
 * 
 */
public class ReposityAction extends DispatchAction {
	private static Log logger = LogFactory.getLog(ReposityAction.class);
    private IReposityService reposityService;

    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReposityForm reposityForm = (ReposityForm) form;

        Reposity reposity = new Reposity();

        reposity.setContractId(reposityForm.getContractId());
        reposity.setGoodsId(reposityForm.getGoodsId());
        reposity.setLogisticNumber(reposityForm.getLogisticNumber());
        reposity.setPurchasePrice(reposityForm.getPurchasePrice());
        reposity.setPurchaseNumber(reposityForm.getPurchaseNumber());
        reposity.setSupplierId(reposityForm.getSupplierId());

        reposity.setStoreTime(System.currentTimeMillis());
        User user = (User) request.getSession().getAttribute("loginUser");
        reposity.setOperatorId(user.getUserID());

        reposityService.save(reposity);

        return mapping.findForward("success");
    }
    
    public ActionForward getGoods(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String goodsidStr = request.getParameter("goodsid");
        String goodsnum = request.getParameter("goodsnum");
        boolean result = reposityService.keeperGetGoods(Long.valueOf(goodsidStr), Integer.valueOf(goodsnum));
        String resultJson = null;
        if (result) {
        	resultJson = "{\"result\":\"true\"}";
		} else {
			resultJson = "{\"result\":\"false\"}";
			logger.info("缺货，邮件通知采购");
		}
		response.setContentType("application/json;charset=UTF-8");
		Writer writer = response.getWriter();
		writer.write(resultJson);
		writer.close();
		return null;
    }

    public void setReposityService(IReposityService reposityService) {
        this.reposityService = reposityService;
    }

}
